import React from 'react';
import PropTypes from 'prop-types';
import { Icon } from 'antd';
import classNames from 'classnames';
import Style from './style.less';

// 只支持单文件上传
class Uploader extends React.Component {
  constructor(props) {
    super(props);
    this.initUploadClient();

    this.state = {
      value: this.props.value || '',
      loadding: false,
      error: '',
    };
  }

  componentWillReceiveProps(nextprops) {
    if (nextprops.value && nextprops.value !== this.state.value) {
      this.setState({ value: nextprops.value, error: '', loadding: false });
    }
  }

  handleChange = (e) => {
    const file = e.target.files[0];
    if (file && this.props.onUpload) {
      // this.props.onUpload 必须返回 Promise
      this.props.onUpload(file).then((val) => {
        // 上传成功
        this.setState(
          { value: val, error: '', loadding: false },
          () => {
            if (this.props.onChange) {
              this.props.onChange(val);
            }
          },
        );
      }).catch((err) => {
        // 上传失败
        this.setState({ error: err });
      });
    }
  }

  handleSubmit = () => {
    this.uploader.click();
  }

  initUploadClient = () => {
    this.uploader = window.document.createElement('input');
    this.uploader.type = 'file';
    this.uploader.onchange = this.handleChange;
    this.uploader.accept = this.props.accept || '';
  }

  render() {
    const propsClass = this.props.className || 'lao-undefined';

    return (
      <div
        className={classNames({
          [`${Style['lao-uploader']}`]: true,
          [`${propsClass}`]: !!this.props.className,
        })}
        style={this.props.style || {}}
        onClick={this.handleSubmit}
      >
        {
          this.state.value &&
          !this.state.loadding &&
          (<img className={Style.pic} src={this.state.value} alt="" />)
        }
        {
          !this.state.value &&
          !this.state.loadding &&
          (<span><Icon type="plus" /></span>)
        }
        {
          this.state.loadding &&
          (<span><Icon type="loadding" /></span>)
        }
        {
          this.state.error &&
          (<em className={Style.error}>{this.state.error}</em>)
        }
      </div>
    );
  }
}

Uploader.propTypes = {
  value: PropTypes.string, // eslint-disable-line
  accept: PropTypes.string, // eslint-disable-line
  onChange: PropTypes.func, // eslint-disable-line
  onUpload: PropTypes.func, // eslint-disable-line
  className: PropTypes.string, // eslint-disable-line
  style: PropTypes.object, // eslint-disable-line
};

export default Uploader;
